package com.pandora.util;

import java.lang.reflect.Field;

import com.pandora.exception.UtilException;


public class DomainUtil {
	public static void setDeclaredFieldValue(Object obj, String fieldName,
			Object fieldValue) throws UtilException {
		Class<?> clazz = obj.getClass();
		Field field = null;
		try {
			// 按名字获取自己定义的或继承的Field
			field = clazz.getDeclaredField(fieldName);
			// 将字段的私有化检查关闭
			if (!field.isAccessible()) {
				field.setAccessible(true);
			}
			field.set(obj, fieldValue);
		} catch (SecurityException e) {
			throw new UtilException("字段访问受限", e);
		} catch (NoSuchFieldException e) {
			throw new UtilException("访问字段不存在", e);
		} catch (IllegalArgumentException e) {
			throw new UtilException("设值字段时错误，值类型与字段类型不匹配", e);
		} catch (IllegalAccessException e) {
			throw new UtilException("为字段注入值时权限受限", e);
		}
	}

	public static Object getDeclaredFieldValue(Object obj, String fieldName)
			throws UtilException {
		Class<?> clazz = obj.getClass();
		Object object = null;
		Field field = null;
		// 按名字获取自己定义的或继承的Field
		try {
			field = clazz.getDeclaredField(fieldName);
			// 将字段的私有化检查关闭
			if (!field.isAccessible()) {
				field.setAccessible(true);
			}
			object = field.get(obj);
		} catch (SecurityException e) {
			throw new UtilException("字段访问受限", e);
		} catch (NoSuchFieldException e) {
			throw new UtilException("访问字段不存在", e);
		} catch (IllegalArgumentException e) {
			throw new UtilException("获取字段时，对象参数错误", e);
		} catch (IllegalAccessException e) {
			throw new UtilException("获取字段值时权限受限", e);
		}
		return object;
	}
}
